//
//  ChangePasswordViewController.m
//  DataStatistics
//
//  Created by oilklenze on 16/1/28.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "ChangePasswordViewController.h"
#import "LoginVC.h"
#import "MBProgressHUD.h"
#import "MoreViewController.h"
#import "isPhoneNumber.h"
#import "UITextField+LolitaText.h"
#import "ChangePasswordModel.h"
#import "ChangePasswordViewModel.h"


@interface ChangePasswordViewController () <UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField         * oldPassword;
@property (strong, nonatomic) IBOutlet UITextField         * newpasswordssss;
@property (strong, nonatomic) IBOutlet UITextField         * surePassword;
@property (strong, nonatomic) NSMutableDictionary          * parameter;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint  * statusConstraint;

@end

@implementation ChangePasswordViewController

- (void)viewDidLoad
{
    self.oldPassword.delegate     = self;
    self.newpasswordssss.delegate = self;
    self.surePassword.delegate    = self;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Nav_Bar"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
    [super viewDidLoad];

    [self changeClearButton:self.oldPassword];
    [self changeClearButton:self.newpasswordssss];
    [self changeClearButton:self.surePassword];
    
    self.oldPassword.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Your old password", nil)
                                                                             attributes:@{
                                                                                          NSForegroundColorAttributeName :  [UIColor colorWithWhite:144/255.0f alpha:1.0f],
                                                                                          NSFontAttributeName : [UIFont systemFontOfSize:12],
                                                                                          NSBaselineOffsetAttributeName :@(-1)
                                                                                          
                                                                                          }];
    
    self.newpasswordssss.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"New password with 6~12 characters", nil)
                                                                                 attributes:@{
                                                                                              NSForegroundColorAttributeName :  [UIColor colorWithWhite:144/255.0f alpha:1.0f],
                                                                                              NSFontAttributeName : [UIFont systemFontOfSize:11],
                                                                                              NSBaselineOffsetAttributeName :@(-1)
                                                                                              }];
    
    self.surePassword.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedString(@"Confirm password", nil)
                                                                              attributes:@{
                                                                                           NSForegroundColorAttributeName :  [UIColor colorWithWhite:144/255.0f alpha:1.0f],
                                                                                           NSFontAttributeName : [UIFont systemFontOfSize:12],
                                                                                           NSBaselineOffsetAttributeName :@(-1)
                                                                                           }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.oldPassword becomeFirstResponder];
}

- (void)changeClearButton:(UITextField*)textfied {
    UIButton* clearButton = [textfied valueForKey:@"_clearButton"];
    [clearButton setImage:[UIImage imageNamed:@"关闭按钮"] forState:UIControlStateNormal];
    [clearButton setImage:[UIImage imageNamed:@"关闭按钮-on"] forState:UIControlStateHighlighted];
}

- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
    [self.view endEditing:YES];
}

#pragma mark-----代理
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    if (textField.tag == 2) {
        [self OK:nil];
    }
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField*)textField
{
    if (textField.tag == 3) {
        [self moveView:-40];
    }
}

- (void)textFieldDidEndEditing:(UITextField*)textField
{
    if (textField.tag == 3) {
        [self moveView:40];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    return newString.length<13;
    
}

- (void)moveView:(float)move {
    //    if (SCREEN_HEIGHT==480) {
    //
    //    NSTimeInterval animationDuration = 0.3f;
    //    CGRect frame = self.view.frame;
    //    frame.origin.y += move;
    //    [UIView beginAnimations:@"ResizeView" context:nil];
    //    [UIView setAnimationDuration:animationDuration];
    //    self.view.frame =frame;
    //    move==- 40? (self.statusConstraint.constant=0) :(self.statusConstraint.constant=16);
    //    [UIView commitAnimations];
    //    }
}

- (IBAction)cancal:(UIBarButtonItem*)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)OK:(id)sender
{
    NSString *oldPassword, *newPassword, *confirmpassword;
    oldPassword     = self.oldPassword.text;
    newPassword     = self.newpasswordssss.text;
    confirmpassword = self.surePassword.text;

    NSString *str;
    if ([isPhoneNumber  illegalCharacter:confirmpassword] || [isPhoneNumber  illegalCharacter:newPassword]) {
        str  = NSLocalizedString(@"The password contains illegal characters",nil);
    }else if ([confirmpassword length] <6 && [newPassword length]<6) {
        str = NSLocalizedString(@"Please enter 6-12 characters",nil);
    }else if ([confirmpassword isEqualToString:newPassword]) {
        [self.parameter setValue:oldPassword forKey:@"oldPwd"];
        [self.parameter setValue:newPassword forKey:@"newPwd"];
        [self dataRequestChangePassword];
        return;
    }
    else {
        str = NSLocalizedString(@"Passwords do not match",nil);
    };

    [MBProgressHUD yty_showErrorWithTitle:nil detailsText:str toView:nil];
}

//发起请求
- (void)dataRequestChangePassword
{
    [ChangePasswordViewModel requestWithUrlForChangePassword:self andParam:self.parameter success:^(ChangePasswordModel *model) {
             NSString* string = [NSString stringWithFormat:@"%@", model.updateResult];
             [self showAlert:string];
    } failure:^(NSString *error) {
         [MBProgressHUD yty_showErrorWithTitle:nil detailsText:error toView:nil];
    }];
}




/** 修改密码 */
- (void)showAlert:(NSString*)retureData
{
    NSDictionary* dic = @{
                          @"0" :NSLocalizedString( @"Permission denied",nil),
                          @"1" :NSLocalizedString( @"Password error",nil),
                          @"2" :NSLocalizedString( @"Password set successful",nil),
                          @"3" :NSLocalizedString(@"Server is not connected",nil),
                          @"4" :NSLocalizedString( @"Password error",nil),
                          @"5" :NSLocalizedString( @"Server is not connected",nil)
                          };
    NSString* tis = dic[retureData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];

        [MBProgressHUD yty_showErrorWithTitle:nil detailsText:tis toView:nil];

        
    });

    if ([retureData isEqualToString:@"2"]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MoreViewController logout:self];
        });
    }
}




- (NSMutableDictionary*)parameter
{
    if (!_parameter) {
        NSString  *str = USERCODE;
        _parameter = @{ @"user_id" : str};
        _parameter = [_parameter mutableCopy];
    }
    return _parameter;
}
@end
